package com.sz.mes.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.sz.mes.entity.ProductTask;
import com.sz.mes.entity.PurchaseOrder;
import com.sz.mes.entity.TableHead;
import com.sz.mes.mapper.ProductTaskMapper;
import com.sz.mes.mapper.PurchaseOrderMapper;
import com.sz.mes.mapper.TableHeadMapper;
import com.sz.mes.service.PurchaseOrderService;
import com.sz.mes.service.impl.BaseCustomServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 采购订单相关Service实现
 *
 * @author hem
 * @version 1.0
 * @date 2023-09-05
 * Copyright © szhs
 */
@Service
@Slf4j
public class PurchaseOrderServiceImpl extends BaseCustomServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements PurchaseOrderService {

    private final PurchaseOrderMapper purchaseOrderMapper;
    private final TableHeadMapper tableHeadMapper;


    public PurchaseOrderServiceImpl(PurchaseOrderMapper purchaseOrderMapper, TableHeadMapper tableHeadMapper) {
        this.purchaseOrderMapper = purchaseOrderMapper;
        this.tableHeadMapper = tableHeadMapper;
    }

    public JsonResult insert(PurchaseOrder entity) {
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        purchaseOrder.setExcelData(entity.getExcelData());
        try {
//            productTaskMapper.insert(productTask);
            if (purchaseOrder.getExcelData() != null) {
                return dataProcess(purchaseOrder.getExcelData(), purchaseOrder.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonResult.OK("导入数据成功");
    }



    //Excel 数据解析导入基础表
    JsonResult dataProcess(String excelData, Long purchaseOrderId) throws ParseException {
        //mapList 获取到所有的数据
        ArrayList<Map<String, String>> mapList = new ArrayList<>();


        //hashMap 表头对应的 序号
        HashMap<String, String> hashMap = new HashMap<>();
        //获取表头
        TableHead tableHead = tableHeadMapper.selectById(4);

        String data = tableHead.getData();
//        String replaceAll = data.replaceAll("\\\\", "");
//        System.out.println(data);
//        System.out.println(replaceAll);

        JSONObject jsonObject = JSONObject.parseObject(tableHead.getData());
        for (Object map : jsonObject.entrySet()) {
//            hashMap.put(String.valueOf(((Map.Entry)map).getValue()),String.valueOf(((Map.Entry)map).getKey()));
            hashMap.put(String.valueOf(((Map.Entry) map).getKey()), String.valueOf(((Map.Entry) map).getValue()));
        }

        //获取完表头信息后清楚数据，给其他数据用
        mapList.clear();

        System.out.println("excelData:" + excelData);

        //json转为List
        JSONArray objects = JSONObject.parseArray(excelData);
//        JSONArray objects = JSONObject.parseArray(JSONObject.toJSONString(excelData));
        for (Object object : objects) {
            HashMap<String, String> map1 = JSONObject.parseObject(JSONObject.toJSONString(object), HashMap.class);
            mapList.add(map1);
        }

        System.out.println("mapList:" + mapList);

        for (Map map : mapList) {
            System.out.println(map);
            //任务单
            PurchaseOrder purchaseOrder = new PurchaseOrder();
            purchaseOrder.setSourceNum((String) map.get(hashMap.get("来源单据号")));
            purchaseOrder.setSourceNumRow((String) map.get(hashMap.get("来源单据行号")));
            purchaseOrder.setRowState((String) map.get(hashMap.get("行状态")));
            purchaseOrder.setPlanNum(((String) map.get(hashMap.get("计划号"))));
            purchaseOrder.setProductNum((String) map.get(hashMap.get("料号")));
            purchaseOrder.setProductName((String) map.get(hashMap.get("料品名称")));
            purchaseOrder.setSpecification((String) map.get(hashMap.get("料品规格")));
            purchaseOrder.setUnit((String) map.get(hashMap.get("采购订单行.采购单位")));
//            purchaseOrder.setRequireNum((Long) map.get(hashMap.get("需求数量")));
//            purchaseOrder.setFactNum((Long) map.get(hashMap.get("确认数量")));
            purchaseOrder.setReceiptNum((String) map.get(hashMap.get("单据编号")));
            purchaseOrder.setRowNum((String) map.get(hashMap.get("行号")));
            purchaseOrder.setPurchasePerson((String) map.get(hashMap.get("采购业务员")));
//            purchaseOrder.setBusinessDate((Date) map.get(hashMap.get("业务日期")));
//            purchaseOrder.setDeliveryDate((Date) map.get(hashMap.get("交期")));
            purchaseOrder.setArrivalDate((String) map.get(hashMap.get("申请到货日期")));
            purchaseOrder.setSupplierName(((String) map.get(hashMap.get("供应商简称"))));

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!" ".equals(map.get(hashMap.get("业务日期"))) && !" ".equals(map.get(hashMap.get("交期")))) {
                String deliveryTime = (String) (map.get(hashMap.get("业务日期")));
                String businessTime = (String) (map.get(hashMap.get("交期")));
                Date deliveryDate = sdf.parse(deliveryTime);
                Date businessDate = sdf.parse(businessTime);
                purchaseOrder.setDeliveryDate(deliveryDate);
                purchaseOrder.setBusinessDate(businessDate);
            }

            Integer requireNum = (Integer) map.get(hashMap.get("需求数量"));
//            Integer taskQuantity = (Integer) map.get(hashMap.get("生产数量"));
            if (requireNum != 0) {
                purchaseOrder.setRequireNum(requireNum);
            } else {
                purchaseOrder.setRequireNum(0);
//                productTask.setQuantity(0);
            }

            Integer factNum = (Integer) map.get(hashMap.get("确认数量"));
//            Integer taskQuantity = (Integer) map.get(hashMap.get("生产数量"));
            if (factNum != 0) {
                purchaseOrder.setFactNum(factNum);
            } else {
                purchaseOrder.setFactNum(0);
//                productTask.setQuantity(0);
            }

            try {
//                purchaseOrder.setExcelData(excelData);
                purchaseOrderMapper.insert(purchaseOrder);
            } catch (Exception e) {
                return JsonResult.FAIL_OPERATION("插入失败" + e.getMessage());
            }
            //任务单处理结束
        }

        return JsonResult.OK("数据导入成功");
    }

    @Override
    public List<String> filterDuplicate(List<String> receiptNumAndRowList) {
        if (V.isEmpty(receiptNumAndRowList)) {
            return Collections.emptyList();
        }

        List<String> duplicateData = purchaseOrderMapper.selectDuplicateData(receiptNumAndRowList);
//        LambdaQueryWrapper<ProductTask> wrapper = new LambdaQueryWrapper<>();
//        wrapper.in(ProductTask::getSplice, receiptNumAndStockNumList);
//        List<String> receiptNumAndStockNumLists = getValuesOfField(productTaskQueryWrapper, ProductTask::getSplice);


        return duplicateData;
    }
}
